package com.twb.quartz.controller;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.twb.core.base.Result;
import com.twb.core.base.controller.BaseController;
import com.twb.core.base.entity.TwbPageInfo;
import com.twb.core.constants.TwbConstants;
import com.twb.core.util.BeanUtils;
import com.twb.core.util.Results;
import com.twb.quartz.entity.twbQuartzJob.TwbQuartzJob;
import com.twb.quartz.entity.twbQuartzJob.dto.GetTwbQuartzJobByIdDto;
import com.twb.quartz.entity.twbQuartzJob.dto.SearchTwbQuartzJobDto;
import com.twb.quartz.entity.twbQuartzJob.vo.SaveTwbQuartzJobVo;
import com.twb.quartz.entity.twbQuartzJob.vo.SearchTwbQuartzJobVo;
import com.twb.quartz.entity.twbQuartzJob.vo.UpdateTwbQuartzJobByIdVo;
import com.twb.quartz.service.ITwbQuartzJobService;
import com.twb.quartz.util.CronUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @Title  TwbQuartzJobController
 * @Description 定时任务
 * 
 * @author DSY
 * @date 2021-12-26 10:46:41
 */
@RestController
@RequestMapping("/quartz/twbQuartzJob")
@Api(tags = "定时任务", value = "TwbQuartzJobController")
public class TwbQuartzJobController extends BaseController {
	@Autowired
	ITwbQuartzJobService twbQuartzJobService;

	/**
	 * @Title  search
	 * @Description 分页查询
	 * @param vo
	 * @return
	 * @author DSY
	 * @date 2021-12-26 10:46:41
	 */
	@GetMapping("/search")
	@ApiOperation(value = "分页查询")
	public Result<TwbPageInfo<SearchTwbQuartzJobDto>> search(SearchTwbQuartzJobVo vo) {
		TwbPageInfo<SearchTwbQuartzJobDto> result = twbQuartzJobService.searchTwbQuartzJob(vo);
		return Results.successWithData(result);
	}

	/**
	 * @Title  getById
	 * @Description 根据ID获取详情
	 * @param id
	 * @return
	 * @author DSY
	 * @date 2021-12-26 10:46:41
	 */
	@GetMapping("/getById")
	@ApiOperation(value = "根据ID获取详情")
	public Result<GetTwbQuartzJobByIdDto> getById(
			@NotBlank @RequestParam @ApiParam(value = "主键", name = "id", required = true) String id) {
		TwbQuartzJob twbQuartzJob = twbQuartzJobService.getById(id);
		if (twbQuartzJob == null) {
			return Results.failure("数据不存在");
		}
		GetTwbQuartzJobByIdDto dto = new GetTwbQuartzJobByIdDto();
		BeanUtils.copyNotNullProperties(twbQuartzJob, dto);
		return Results.successWithData(dto);
	}

	/**
	 * @Title  save
	 * @Description 保存信息
	 * @param vo
	 * @return
	 * @author DSY
	 * @date 2021-12-26 10:46:41
	 */
	@PostMapping("/save")
	@ApiOperation(value = "保存信息")
	public Result<String> save(@Valid @RequestBody SaveTwbQuartzJobVo vo) {
		if (!CronUtils.isValid(vo.getCronExpression())) {
			return Results.failure("任务创建失败！cron表达式格式错误");
		}
		if (StringUtils.containsIgnoreCase(vo.getInvokeTarget(), TwbConstants.LOOKUP_RMI)) {
			return Results.failure("任务创建失败！目标字符串不允许'rmi://'调用");
		}
		if (StringUtils.containsIgnoreCase(vo.getInvokeTarget(), TwbConstants.LOOKUP_LDAP)) {
			return Results.failure("任务创建失败！目标字符串不允许'ldap://'调用");
		}
		if (StringUtils.containsAnyIgnoreCase(vo.getInvokeTarget(),
				new String[] { TwbConstants.HTTP, TwbConstants.HTTPS })) {
			return Results.failure("任务创建失败！目标字符串不允许'http(s)//'调用");
		}
		boolean result;
		try {
			result = twbQuartzJobService.saveTwbQuartzJob(vo);
		} catch (SchedulerException e) {
			return Results.failure("任务创建失败！" + e.getMessage());
		}
		if (result) {
			return Results.success("任务创建成功");
		} else {
			return Results.failure("任务创建失败");
		}
	}

	/**
	 * @Title  updateById
	 * @Description 更新信息
	 * @param vo
	 * @return
	 * @author DSY
	 * @date 2021-12-26 10:46:41
	 */
	@PutMapping("/updateById")
	@ApiOperation(value="更新信息")
	public Result<String> updateById(@Valid @RequestBody UpdateTwbQuartzJobByIdVo vo){
		if (!CronUtils.isValid(vo.getCronExpression())) {
			return Results.failure("任务更新失败！cron表达式格式错误");
		}
		if (StringUtils.containsIgnoreCase(vo.getInvokeTarget(), TwbConstants.LOOKUP_RMI)) {
			return Results.failure("任务更新失败！目标字符串不允许'rmi://'调用");
		}
		if (StringUtils.containsIgnoreCase(vo.getInvokeTarget(), TwbConstants.LOOKUP_LDAP)) {
			return Results.failure("任务更新失败！目标字符串不允许'ldap://'调用");
		}
		if (StringUtils.containsAnyIgnoreCase(vo.getInvokeTarget(),
				new String[] { TwbConstants.HTTP, TwbConstants.HTTPS })) {
			return Results.failure("任务更新失败！目标字符串不允许'http(s)//'调用");
		}
		boolean result;
		try {
			result = twbQuartzJobService.updateTwbQuartzJobById(vo);
		} catch (SchedulerException e) {
			return Results.failure("任务更新失败！" + e.getMessage());
		}
		if(result) {
			return Results.success("更新成功");
		}else {
			return Results.failure("更新失败");
		}
	}

	/**
	 * @Title  deleteById
	 * @Description 删除信息
	 * @param id
	 * @return
	 * @author DSY
	 * @date 2021-12-26 10:46:41
	 */
	@PostMapping("/deleteById")
	@ApiOperation(value="删除信息")
	public Result<String> deleteById(
			@NotBlank
			@RequestParam
			@ApiParam(value="主键",name="id",required=true)
			String id){
		boolean result;
		try {
			result = twbQuartzJobService.deleteTwbQuartzJobById(id);
		} catch (SchedulerException e) {
			return Results.failure("任务删除失败！" + e.getMessage());
		}
		if(result) {
			return Results.success("删除成功");
		}else {
			return Results.failure("删除失败");
		}
	}

	/**
	 * @Title  deleteBatchByIds
	 * @Description 批量删除信息
	 * @param ids
	 * @return
	 * @author DSY
	 * @date 2021-12-26 10:46:41
	 */
	@PostMapping("/batchDeleteByIds")
	@ApiOperation(value="批量删除信息")
	public Result<String> deleteBatchByIds(
			@NotBlank
			@RequestParam
			@ApiParam(value="主键集合",name="ids",required=true)
			String ids){
		int result;
		try {
			result = twbQuartzJobService.deleteTwbQuartzJobByIds(ids);
		} catch (SchedulerException e) {
			return Results.failure("任务删除失败！" + e.getMessage());
		}
		if(result>0) {
			return Results.success("删除成功");
		}else {
			return Results.failure("删除失败");
		}
	}

	
	/**
	 * @Title  exportExcel
	 * @Description 导出excel
	 * @param exportExcelVo
	 * @param searchVo
	 * @param request
	 * @return
	 * @throws Exception
	 * @author DSY
	 * @date 2021-12-26 10:46:41
	 */
	@GetMapping("/exportExcel")
	@ApiOperation(value="导出excel")
	public void exportExcel(SearchTwbQuartzJobVo vo, HttpServletResponse response) throws Exception{
		twbQuartzJobService.exportExcel(vo, response);
	}
	
	/**
	 * @Title changeStatus
	 * @Description 更新任务状态（1：正常；2：暂停）
	 * @param id
	 * @param status
	 * @return
	 * @author DSY
	 * @date 2021年12月26日 下午8:58:27
	 */
	@PostMapping("/changeStatus")
	@ApiOperation(value="更新任务状态（1：正常；2：暂停）")
	public Result<String> changeStatus(
			@NotBlank
			@RequestParam
			@ApiParam(value="主键",name="id",required=true)
			String id,
			@NotBlank
			@RequestParam
			@ApiParam(value="状态",name="status",required=true)
			String status){
		try {
			boolean result = twbQuartzJobService.chageStatus(id, status);
			if(result) {
				return Results.success("状态更新成功");
			}else {
				return Results.failure("状态更新失败");
			}
		} catch (SchedulerException e) {
			return Results.failure("状态更新失败！"+e.getMessage());
		}
	}
	
	/**
	 * @Title runJob
	 * @Description 定时任务立即执行一次
	 * @param id
	 * @return
	 * @author DSY
	 * @date 2021年12月26日 下午9:01:26
	 */
	@PostMapping("/runOnceJob")
	@ApiOperation(value="定时任务立即执行一次")
	public Result<String> runJob(
			@NotBlank
			@RequestParam
			@ApiParam(value="主键",name="id",required=true)
			String id){
		try {
			twbQuartzJobService.runJob(id);
			return Results.success("任务执行成功");
		} catch (SchedulerException e) {
			return Results.failure("任务执行失败！"+e.getMessage());
		}
	}
}